package com.njzxw.fs.serverAdmin;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.eureka.util.StatusInfo;
import de.codecentric.boot.admin.server.domain.entities.Instance;
import de.codecentric.boot.admin.server.domain.entities.InstanceRepository;
import de.codecentric.boot.admin.server.domain.events.InstanceDeregisteredEvent;
import de.codecentric.boot.admin.server.domain.events.InstanceEvent;
import de.codecentric.boot.admin.server.domain.events.InstanceStatusChangedEvent;
import de.codecentric.boot.admin.server.domain.values.InstanceId;
import de.codecentric.boot.admin.server.notify.AbstractEventNotifier;
import de.codecentric.boot.admin.server.notify.Notifier;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;
import reactor.core.Disposable;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
import reactor.core.scheduler.Schedulers;
import reactor.retry.Retry;

import java.time.Duration;
import java.time.Instant;
import java.util.Arrays;
import java.util.concurrent.ConcurrentHashMap;
import java.util.logging.Level;

public class DdNotifier extends AbstractEventNotifier {
    private static final Logger log = LoggerFactory.getLogger(DdNotifier.class);
    private final ConcurrentHashMap<InstanceId, DdNotifier.Reminder> reminders = new ConcurrentHashMap<>();
    private final Notifier delegate;
    private Duration checkReminderInverval = Duration.ofSeconds(10);
    private Duration reminderPeriod = Duration.ofMinutes(10);
    private String[] reminderStatuses = {"DOWN", "OFFLINE"};
    private Disposable subscription;

    public DdNotifier(Notifier delegate, InstanceRepository repository) {
        super(repository);
        Assert.notNull(delegate, "'delegate' must not be null!");
        this.delegate = delegate;
    }

    @Override
    public Mono<Void> doNotify(InstanceEvent event, Instance instance) {
        return delegate.notify(event).onErrorResume(error -> Mono.empty()).then(Mono.fromRunnable(() -> {
            if (shouldEndReminder(event)) {
                reminders.remove(event.getInstance());
            } else if (shouldStartReminder(event)) {
                reminders.putIfAbsent(event.getInstance(), new DdNotifier.Reminder(event));
            }
        }));
    }


    public void start() {
        this.subscription = Flux.interval(this.checkReminderInverval, Schedulers.newSingle("reminders"))
                .log(log.getName(), Level.FINEST)
                .doOnSubscribe(subscription -> log.debug("Started reminders"))
                .flatMap(i -> this.sendReminders())
                .retryWhen(Retry.any()
                        .retryMax(Integer.MAX_VALUE)
                        .doOnRetry(
                                ctx -> log.error("Resubscribing for reminders after uncaught error",
                                        ctx.exception())))
                .subscribe();
    }

    public void stop() {
        if (this.subscription != null && !this.subscription.isDisposed()) {
            log.debug("stopped reminders");
            this.subscription.dispose();
        }
    }

    protected Mono<Void> sendReminders() {
        Instant now = Instant.now();

        return Flux.fromIterable(this.reminders.values())
                .filter(reminder -> reminder.getLastNotification().plus(reminderPeriod).isBefore(now))
                .flatMap(reminder -> delegate.notify(reminder.getEvent())
                        .doOnSuccess(signal -> reminder.setLastNotification(now)))
                .then();
    }

    protected boolean shouldStartReminder(InstanceEvent event) {
        if (event instanceof InstanceStatusChangedEvent) {
            return Arrays.binarySearch(reminderStatuses,
                    ((InstanceStatusChangedEvent) event).getStatusInfo().getStatus()) >= 0;
        }
        return false;
    }

    protected boolean shouldEndReminder(InstanceEvent event) {
        if (event instanceof InstanceDeregisteredEvent) {
            return true;
        }
        if (event instanceof InstanceStatusChangedEvent) {
            return Arrays.binarySearch(reminderStatuses,
                    ((InstanceStatusChangedEvent) event).getStatusInfo().getStatus()) < 0;
        }
        return false;
    }

    public void setReminderPeriod(Duration reminderPeriod) {
        this.reminderPeriod = reminderPeriod;
    }

    public void setReminderStatuses(String[] reminderStatuses) {
        String[] copy = Arrays.copyOf(reminderStatuses, reminderStatuses.length);
        Arrays.sort(copy);
        this.reminderStatuses = copy;
    }

    public void setCheckReminderInverval(Duration checkReminderInverval) {
        this.checkReminderInverval = checkReminderInverval;
    }

    private static class Reminder {
        private final InstanceEvent event;
        private Instant lastNotification;

        private Reminder(InstanceEvent event) {
            this.event = event;
            this.lastNotification = event.getTimestamp();
        }

        public void setLastNotification(Instant lastNotification) {
            this.lastNotification = lastNotification;
        }

        public Instant getLastNotification() {
            return lastNotification;
        }

        public InstanceEvent getEvent() {
            return event;
        }
    }
}
